/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.web.web;

import com.google.common.collect.Lists;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.web.entity.WxAgents;
import com.jeeplus.modules.web.entity.WxOrder;
import com.jeeplus.modules.web.mapper.WxAgentsMapper;
import com.jeeplus.modules.web.mapper.WxOrderMapper;
import com.jeeplus.modules.web.service.WxAgentsRecordingService;
import com.jeeplus.modules.web.service.WxOrderService;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 订单管理Controller
 * @author rongjie
 * @version 2017-08-06
 */
@Controller
@RequestMapping(value = "${adminPath}/web/wxOrder")
public class WxOrderController extends BaseController {

	@Autowired
	private WxOrderService wxOrderService;
	@Autowired
	private WxOrderMapper wxOrderMapper;
	@Autowired
	private WxAgentsMapper wxAgentsMapper;
	@Autowired
	private WxAgentsRecordingService wxAgentsRecordingService;

	@ModelAttribute
	public WxOrder get(@RequestParam(required=false) String id) {
		WxOrder entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = wxOrderService.get(id);
		}
		if (entity == null){
			entity = new WxOrder();
		}
		return entity;
	}

	/**
	 * 订单管理列表页面
	 */
	@RequiresPermissions("web:wxOrder:list")
	@RequestMapping(value = {"list", ""})
	public String list(Model model) {

		return "modules/web/wxOrderList";
	}

		/**
	 * 订单管理列表数据
	 */
	@ResponseBody
	@RequiresPermissions("web:wxOrder:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(WxOrder wxOrder, HttpServletRequest request, HttpServletResponse response, Model model) {
		User currentUser = UserUtils.getUser();
		WxAgents wxAgents=null;

		//非管理员账户，能查看自己或下层代理所绑定设备的全部订单信息
		if(!currentUser.getId().equals("1")){
			WxAgents agents = new WxAgents();
			wxAgents=wxAgentsMapper.findUniqueByProperty("username", currentUser.getMobile());
			agents.setId(wxAgents.getId());
			if(wxOrder.getAgents()!=null && wxOrder.getAgents().getUserName()!=null && !"".equals(wxOrder.getAgents().getUserName())){
				agents.setUserName(wxOrder.getAgents().getUserName());
			}

			//wxAgentsMapper.findUniqueByProperty("username", currentUser.getMobile());
			//wxAgents.setUserName(currentUser.getMobile());
			wxOrder.setAgents(agents);

		}
		if(wxOrder.getTime()==null){
			wxOrder.setTime(new Date());
		}
		if(wxOrder.getEndTime()==null){
			wxOrder.setEndTime(new Date());
		}

		Page<WxOrder> page = wxOrderService.findPage(new Page<WxOrder>(request, response), wxOrder);

		return getBootstrapData(page);
	}

	/**
	 * 查看，增加，编辑订单管理表单页面
	 */
	@RequiresPermissions(value={"web:wxOrder:view","web:wxOrder:add","web:wxOrder:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WxOrder wxOrder, Model model) {
		model.addAttribute("wxOrder", wxOrder);
		if(StringUtils.isBlank(wxOrder.getId())){//如果ID是空为添加
			model.addAttribute("isAdd", true);
		}

		return "modules/web/wxOrderForm";
	}

	/**
	 * 保存订单管理
	 */
	@RequiresPermissions(value={"web:wxOrder:add","web:wxOrder:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(WxOrder wxOrder, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, wxOrder)){
			return form(wxOrder, model);
		}
		//新增或编辑表单保存
		wxOrderService.save(wxOrder);//保存
		addMessage(redirectAttributes, "保存订单管理成功");
		return "redirect:"+Global.getAdminPath()+"/web/wxOrder/?repage";
	}

	/**
	 * 删除订单管理
	 */
	@ResponseBody
	@RequiresPermissions("web:wxOrder:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(WxOrder wxOrder, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		wxOrderService.delete(wxOrder);
		j.setMsg("删除订单管理成功");
		return j;
	}

	/**
	 * 批量删除订单管理
	 */
	@ResponseBody
	@RequiresPermissions("web:wxOrder:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			wxOrderService.delete(wxOrderService.get(id));
		}
		j.setMsg("删除订单管理成功");
		return j;
	}

	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("web:wxOrder:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public AjaxJson exportFile(WxOrder wxOrder, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "订单管理"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<WxOrder> page = wxOrderService.findPage(new Page<WxOrder>(request, response, -1), wxOrder);
    		new ExportExcel("订单管理", WxOrder.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出订单管理记录失败！失败信息："+e.getMessage());
		}
			return j;
    }
	/**
	 * 金额
	 */
	@ResponseBody
	@RequestMapping(value = "getMoney")
	public AjaxJson getMoney(String time,String endTime) {
		AjaxJson j = new AjaxJson();
		long ti=time==null?0L:Long.valueOf(time);
		long en=endTime==null?0L:Long.valueOf(endTime);
//		wxAdminOrderService.delete(wxAdminOrder);
		Timestamp setTime=new Timestamp(ti);
		Timestamp timeEnd=new Timestamp(en);
		User currentUser = UserUtils.getUser();
		WxAgents wxAgents=null;

		//非管理员账户，能查看自己或下层代理所绑定设备的全部统计信息
		if(!currentUser.getId().equals("1")){
			wxAgents=wxAgentsMapper.findUniqueByProperty("username", currentUser.getMobile());
			//wxAgents.setUserName(currentUser.getMobile());
		}
//		Double s1=wxOrderMapper.getOrderTimeTotal(setTime,timeEnd,1,wxAgents);
		Double s2=wxOrderMapper.getOrderTimeTotal(setTime,timeEnd,0  ,wxAgents);
		Double s3=wxOrderMapper.getOrderTimeTotal(setTime,timeEnd,2  ,wxAgents);
		Double s4=wxOrderMapper.getOrderTimeTotal(setTime,timeEnd,4  ,wxAgents);
		LinkedHashMap<String,Object> map=new LinkedHashMap<>();
//	 	map.put("s1",s1);
	 	map.put("s2",s2);
	 	map.put("s3",s3);
	 	map.put("s4",s4);
		j.setMsg("查询成功");
		j.setBody(map);
		return j;
	}

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("web:wxOrder:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<WxOrder> list = ei.getDataList(WxOrder.class);
			for (WxOrder wxOrder : list){
				try{
					wxOrderService.save(wxOrder);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条订单管理记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条订单管理记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入订单管理失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/web/wxOrder/?repage";
    }

	/**
	 * 下载导入订单管理数据模板
	 */
	@RequiresPermissions("web:wxOrder:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "订单管理数据导入模板.xlsx";
    		List<WxOrder> list = Lists.newArrayList();
    		new ExportExcel("订单管理数据", WxOrder.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/web/wxOrder/?repage";
    }


	/**
	 * 下载导入订单管理数据模板
	 */
	@RequiresPermissions("web:wxOrder:fenxiao")
	@RequestMapping(value = "fenxiao")
	@ResponseBody
	public AjaxJson fenxiao(WxOrder wxOrder) {
		AjaxJson j = new AjaxJson();

		if(wxOrder.getType().equals("0")){
			wxAgentsRecordingService.saveAgentRecordingForAgents(wxOrder.getEquipment().getNumber(), wxOrder.getOrderNumber(), new Double(wxOrder.getOrderMoney()), new Double(wxOrder.getOrderMoney()));
			j.setMsg("分销订单成功");
		}else{
			j.setSuccess(false);
			j.setMsg("订单类型错误，不能分销");
		}
		return j;
	}
}
